package com.czl.base.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.czl.base.R;

import java.util.ArrayList;
import java.util.List;


public class PieChartView extends View {

    private TextPaint mTextPaint;
    private float mTextWidth;
    private float mTextHeight;
    Paint cPaint;

    float sum2 = 0f;
    /**
     * 饼图半径
     */
    private float pieChartCircleRadius = 100;
    private float pieChartInnerCircleRadius = 45;

    private float textBottom;
    /**
     * 记录文字大小
     */
    private float mTextSize = 14;

    /**
     * 饼图所占矩形区域（不包括文字）
     */
    private RectF pieChartCircleRectF = new RectF();

    /**
     * 饼状图信息列表
     */
    private List<PieceDataHolder> pieceDataHolders = new ArrayList<>();


    /**
     * 标记线长度
     */
    private float markerLineLength = 30f;

    public PieChartView(Context context) {
        super(context);
        init(null, 0);
    }

    public PieChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public PieChartView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.PieChartView, defStyle, 0);

        pieChartCircleRadius = a.getDimension(
                R.styleable.PieChartView_circleRadius,
                pieChartCircleRadius);
        pieChartInnerCircleRadius = a.getDimension(R.styleable.PieChartView_circleInnerRadius, pieChartInnerCircleRadius);
        mTextSize = a.getDimension(R.styleable.PieChartView_textSize, mTextSize) / getResources().getDisplayMetrics().density;

        a.recycle();

        // Set up a default TextPaint object
        mTextPaint = new TextPaint();
        mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextAlign(Paint.Align.LEFT);

        cPaint = new Paint();
        cPaint.setColor(Color.WHITE);
        // Update TextPaint and text measurements from attributes
        invalidateTextPaintAndMeasurements();
    }

    private void invalidateTextPaintAndMeasurements() {

        mTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, getContext().getResources().getDisplayMetrics()));

        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        mTextHeight = fontMetrics.descent - fontMetrics.ascent;
        textBottom = fontMetrics.bottom;
    }

    /**
     * 设置饼状图的半径
     *
     * @param pieChartCircleRadius 饼状图的半径（px）
     */
    public void setPieChartCircleRadius(int pieChartCircleRadius) {

        this.pieChartCircleRadius = pieChartCircleRadius;

        invalidate();
    }

    /**
     * 设置标记线的长度
     *
     * @param markerLineLength 标记线的长度（px）
     */
    public void setMarkerLineLength(int markerLineLength) {
        this.markerLineLength = markerLineLength;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        initPieChartCircleRectF();
        drawAllSectors(canvas);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, pieChartInnerCircleRadius, cPaint);
        drawMarkerText(canvas, String.valueOf((Math.round(sum2))));
    }

    private void drawAllSectors(Canvas canvas) {
        float sum = 0f;
        for (PieceDataHolder pieceDataHolder : pieceDataHolders) {
            sum += pieceDataHolder.value;
        }

        sum2 = 0f;
        for (PieceDataHolder pieceDataHolder : pieceDataHolders) {
            float startAngel = sum2 / sum * 360;
            sum2 += pieceDataHolder.value;
            float sweepAngel = pieceDataHolder.value / sum * 360;

            drawSector(canvas, pieceDataHolder.color, startAngel, sweepAngel);
            drawMarkerLineAndText(canvas, pieceDataHolder.color, startAngel + sweepAngel / 2, pieceDataHolder.marker);
        }
    }

    private void initPieChartCircleRectF() {
        pieChartCircleRectF.left = getWidth() / 2 - pieChartCircleRadius;
        pieChartCircleRectF.top = getHeight() / 2 - pieChartCircleRadius;
        pieChartCircleRectF.right = pieChartCircleRectF.left + pieChartCircleRadius * 2;
        pieChartCircleRectF.bottom = pieChartCircleRectF.top + pieChartCircleRadius * 2;
    }

    /**
     * Gets the example dimension attribute value.
     *
     * @return The example dimension attribute value.(sp)
     */
    public float getTextSize() {
        return mTextSize;
    }

    /**
     * Sets the view's text dimension attribute value. In the PieChartView view, this dimension
     * is the font size.
     *
     * @param textSize The text dimension attribute value to use.(sp)
     */
    public void setTextSize(float textSize) {
        mTextSize = textSize;
        invalidateTextPaintAndMeasurements();
    }

    /**
     * 设置饼状图要显示的数据
     *
     * @param data 列表数据
     */
    public void setData(List<PieceDataHolder> data) {

        if (data != null) {
            pieceDataHolders.clear();
            pieceDataHolders.addAll(data);
        }

        invalidate();
    }

    /**
     * 绘制扇形
     *
     * @param canvas     画布
     * @param color      要绘制扇形的颜色
     * @param startAngle 起始角度
     * @param sweepAngle 结束角度
     */
    protected void drawSector(Canvas canvas, int color, float startAngle, float sweepAngle) {

        Paint paint = new Paint();
//        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
//        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(ringWidth);
        paint.setColor(color);

        canvas.drawArc(pieChartCircleRectF, startAngle, sweepAngle, true, paint);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        initRectF(getMeasuredWidth(), getMeasuredHeight());
    }
    /**
     * 计算圆环的范围
     *
     * @param w
     * @param h
     */
    /**
     * 圆环圆心x坐标
     */
    private int centerX;
    /**
     * 圆环圆心y坐标
     */
    private int centerY;
    /**
     * 圆环范围
     */
    private RectF oval;
    /**
     * 圆环半径，以内环算
     */
    private int innerRadius;
    /**
     * 圆环厚度
     */
    private int ringWidth;

    private void initRectF(int w, int h) {
        if (w == 0 && h == 0) {
            return;
        }
        centerX = (int) ((float) w / 2);
        centerY = (int) ((float) h / 2);
        innerRadius = (int) ((float) w / 2 / 89 * 64);
        ringWidth = (int) ((float) w / 2 / 89 * 25);
        oval = new RectF(centerX - innerRadius, centerY - innerRadius, centerX + innerRadius, centerY + innerRadius);
    }

    protected void drawMarkerText(Canvas canvas, String text) {
        mTextPaint.setColor(Color.parseColor("#333333"));
        mTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 22, getContext().getResources().getDisplayMetrics()));
        float textWidth = mTextPaint.measureText(text);
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        float fontHeight = fontMetrics.descent - fontMetrics.ascent;
        //设置文字居中
        float textBaseY = getHeight() - (getHeight() - fontHeight) / 2 - fontMetrics.bottom * 2;

        canvas.drawText(text, (getWidth() - textWidth) / 2, textBaseY, mTextPaint);

        String text1 = "工单总数";
        mTextPaint.setColor(Color.parseColor("#666666"));
        mTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 11, getContext().getResources().getDisplayMetrics()));
        Paint.FontMetrics fontMetrics1 = mTextPaint.getFontMetrics();
        float fontHeight1 = fontMetrics1.descent - fontMetrics1.ascent;
        float text1Width = mTextPaint.measureText(text1);
        float textBaseY1 = getHeight() - (getHeight() - fontHeight1) / 2 + fontMetrics1.bottom * 3;
        canvas.drawText(text1, (getWidth() - text1Width) / 2, textBaseY1, mTextPaint);
    }

    /**
     * 绘制标注线和标记文字
     *
     * @param canvas      画布
     * @param color       标记的颜色
     * @param rotateAngel 标记线和水平相差旋转的角度
     */
    protected void drawMarkerLineAndText(Canvas canvas, int color, float rotateAngel, String text) {
        Paint paint = new Paint();
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(color);

        Path path = new Path();
        path.close();
        path.moveTo(getWidth() / 2, getHeight() / 2);
        final float x = (float) (getWidth() / 2 + (markerLineLength + pieChartCircleRadius) * Math.cos(Math.toRadians(rotateAngel)));
        final float y = (float) (getHeight() / 2 + (markerLineLength + pieChartCircleRadius) * Math.sin(Math.toRadians(rotateAngel)));
        path.lineTo(x, y);
        float landLineX;
        LogUtils.e(x, y);
        float textWidth = mTextPaint.measureText(text);
        if (270f > rotateAngel && rotateAngel > 90f) {
            landLineX = x - textWidth;
        } else {
            landLineX = x + textWidth;
        }
        path.lineTo(landLineX, y);
        canvas.drawPath(path, paint);

        mTextPaint.setColor(color);
        StaticLayout layout = new StaticLayout(text, mTextPaint, 300,
                Layout.Alignment.ALIGN_CENTER, 1.0F, 0.0F, true);
        canvas.save();
        //别忘了restore
        if (270f > rotateAngel && rotateAngel > 90f) {

//            canvas.drawText(text, landLineX - textWidth, y + mTextHeight / 2 - textBottom, mTextPaint);
//            StaticLayout layout = new StaticLayout(text,mTextPaint, 10, Layout.Alignment.ALIGN_NORMAL, (float) 1.0,(float) 0.0, true);
//
//            canvas.translate(landLineX - textWidth, y + mTextHeight / 2 - textBottom);
//            layout.draw(canvas);
            canvas.translate(landLineX - textWidth, y - textBottom - SizeUtils.dp2px(15f));//从20，20开始画
        } else {
//            StaticLayout layout = new StaticLayout(text,mTextPaint, 10, Layout.Alignment.ALIGN_NORMAL, (float) 1.0,(float) 0.0, true);
//
//            canvas.translate(landLineX, y + mTextHeight / 2 - textBottom);
//            layout.draw(canvas);
//            canvas.drawText(text, landLineX, y + mTextHeight / 2 - textBottom, mTextPaint);
//            TextPaint textPaint = new TextPaint();
//            textPaint.setARGB(0xFF, 0, 0, 0);
//            textPaint.setTextSize(20.0F);
//            textPaint.setAntiAlias(true);

            canvas.translate(landLineX - textWidth * 2, y - textBottom - SizeUtils.dp2px(15f));//从20，20开始画
        }
        layout.draw(canvas);
        canvas.restore();//别忘了restore

    }

    /**
     * 饼状图每块的信息持有者
     */
    public static final class PieceDataHolder {

        /**
         * 每块扇形的值的大小
         */
        private float value;

        /**
         * 扇形的颜色
         */
        private int color;

        /**
         * 每块的标记
         */
        private String marker;


        public float getValue() {
            return value;
        }

        public void setValue(float value) {
            this.value = value;
        }

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }

        public String getMarker() {
            return marker;
        }

        public void setMarker(String marker) {
            this.marker = marker;
        }

        public PieceDataHolder(float value, int color, String marker) {
            this.value = value;
            this.color = color;
            this.marker = marker;
        }
    }

}